有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA:如何从需要启用Cookie的站点下载HTML文件?

我正在尝试从网站下载一个HTML文件。我使用以下简单的方法:

 URL url = new URL("here goes the link to the html file");
 BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
 String htmlfile = "";
 String temp;
 while ((temp = br.readLine()) != null) {
       htmlfile+= temp;
 }

问题是我在htmlfile变量中得到以下字符串:

The installation of ... requires the acceptance of a cookie by your browser    
software.    The cookie is used to ensure that you and only you are 
able to access information ....

换句话说,当从url打开流时,我需要在某种程度上启用cookies。是否可以通过使用URL来实现这一点,或者我需要一种不同的方法?提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    您可以使用^{}^{}对象上设置cookie,例如

    URL url = new URL("here goes the link to the html file");
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Cookie", "here goes the cookie");
    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    

    如果事先不知道cookie,但是通过对以前的HTTP请求的回复设置了cookie,那么可以在表示以前的HTTP交换的URLConnection实例上使用^{}etc来检索cookie